package org.monkey.example.websocket.handler;

import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.monkey.example.websocket.entity.convert.SocketMsgConvert;
import org.monkey.example.websocket.entity.form.SocketMsgAddForm;
import org.monkey.example.websocket.service.SocketMsgService;
import org.monkey.socket.plugin.entity.SocketMsg;
import org.monkey.socket.plugin.service.IMsgSendHandler;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class MsgEventHandler implements IMsgSendHandler, InitializingBean {

  @Autowired
  SocketMsgService socketMsgService;
  @Autowired
  SocketMsgConvert socketMsgConvert;
  @Override
  public void afterPropertiesSet(){
    log.info("msg save handler init success...");
  }

  @Override
  public boolean handlerMsg(ChannelHandlerContext channelHandlerContext, SocketMsg socketMsg) {
    //todo 定义自己的消息处理 存储逻辑
    if (isNeedSave(socketMsg)) {
      SocketMsgAddForm addForm =socketMsgConvert.convert2AddForm(socketMsg);
      log.info("save msg to mysql:{}",addForm);
      socketMsgService.add(addForm);
    } else {
      log.info("this msg is not need save, skip");
    }
    return true;
  }

  boolean isNeedSave(SocketMsg socketMsg){
    return true;
  }
}
